#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_adc.h"
#include "hi_errno.h"

// 宏定义 [cite: 100-105]
#define LED_INTERVAL_TIME_US 200000
#define LED_TASK_STACK_SIZE 4096
#define LED_TASK_PRIO 25
#define LED_TEST_GPIO 10      // LED连接GPIO 10
#define SKEW_DETECT_GPIO 11   // 倾斜传感器连接GPIO 11

// 状态定义 [cite: 106-112]
enum LedState {
    LED_ON = 0,   // 假设低电平点亮，具体看接线，文档中写0
    LED_OFF,
    LED_SPARK,
};

#define SKEW_DETECT_ON 1
#define SKEW_DETECT_OFF 0

// GPIO初始化 [cite: 115-123]
static void SkewDetectInit(void)
{
    // 初始化LED GPIO
    IoTGpioInit(LED_TEST_GPIO);
    hi_io_set_func(LED_TEST_GPIO, HI_IO_FUNC_GPIO_10_GPIO);
    IoTGpioSetDir(LED_TEST_GPIO, IOT_GPIO_DIR_OUT);
    hi_io_set_pull(LED_TEST_GPIO, HI_IO_PULL_UP);
    IoTGpioSetOutputVal(LED_TEST_GPIO, LED_OFF);

    // 初始化传感器 GPIO
    IoTGpioInit(SKEW_DETECT_GPIO);
    hi_io_set_func(SKEW_DETECT_GPIO, HI_IO_FUNC_GPIO_11_GPIO);
    IoTGpioSetDir(SKEW_DETECT_GPIO, IOT_GPIO_DIR_IN);
    hi_io_set_pull(SKEW_DETECT_GPIO, HI_IO_PULL_UP);
}

// 任务处理函数 [cite: 125-143]
static void *SkewDetectTask(const char *arg)
{
    unsigned char ucType;
    (void)arg;
    
    while (1) {
        ucType = 0;
        // 读取传感器状态
        IoTGpioGetInputVal(SKEW_DETECT_GPIO, &ucType);
        printf("SKEW_DETECT_GPIO %d\n", ucType);
        
        // 根据状态控制LED
        if(ucType == SKEW_DETECT_ON)
        {
            IoTGpioSetOutputVal(LED_TEST_GPIO, LED_ON); // 点亮
        }
        else
        {
            IoTGpioSetOutputVal(LED_TEST_GPIO, LED_OFF); // 熄灭
        }
        
        usleep(LED_INTERVAL_TIME_US);
    }
    return NULL;
}

// 入口函数 [cite: 145-158]
static void SkewDetectEntry(void)
{
    osThreadAttr_t attr;
    
    SkewDetectInit();
    
    attr.name = "SkewDetectTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = LED_TASK_STACK_SIZE;
    attr.priority = LED_TASK_PRIO;
    
    if (osThreadNew((osThreadFunc_t)SkewDetectTask, NULL, &attr) == NULL) {
        printf("[SkewDetectEntry] Failed to create SkewDetectTask!\n");
    }
}

// 启动入口 [cite: 160]
SYS_RUN(SkewDetectEntry);